const Order = require('../models/order');
const Product = require('../models/product');
const User = require('../models/user');

const orderController = {
  // 创建订单
  async createOrder(req, res, next) {
    try {
      const buyerId = req.user.userId;
      const { productId, meetingInfo, contactInfo } = req.body;

      // 查找商品
      const product = await Product.findById(productId);
      if (!product) {
        return res.status(404).json({
          success: false,
          message: '商品不存在'
        });
      }

      // 检查商品状态 - 只能购买"在售"的商品
      if (product.status !== '在售') {
        return res.status(400).json({
          success: false,
          message: product.status === '交易中' ? '该商品正在交易中' : '商品已不可购买'
        });
      }

      // 不能购买自己的商品
      if (product.seller.toString() === buyerId) {
        return res.status(400).json({
          success: false,
          message: '不能购买自己的商品'
        });
      }

      // 创建订单
      const order = new Order({
        buyer: buyerId,
        seller: product.seller,
        product: productId,
        price: product.price,
        meetingInfo,
        contactInfo
      });

      await order.save();

      // 更新商品状态为"交易中"
      await Product.findByIdAndUpdate(productId, { status: '交易中' });

      // 返回订单信息
      const populatedOrder = await Order.findById(order._id)
        .populate('buyer', 'username avatar phone')
        .populate('seller', 'username avatar phone')
        .populate('product');

      res.status(201).json({
        success: true,
        message: '订单创建成功',
        data: { order: populatedOrder }
      });
    } catch (error) {
      next(error);
    }
  },

  // 获取订单列表
  async getOrders(req, res, next) {
    try {
      const userId = req.user.userId;
      const {
        role = 'all',  // 'all', 'buyer', 'seller'
        status,        // 订单状态筛选
        page = 1,
        limit = 10,
        sort = 'createdAt', // 排序字段
        order = 'desc'      // 排序方向
      } = req.query;

      // 构建查询条件
      const query = {};

      // 根据角色筛选
      if (role === 'buyer') {
        query.buyer = userId;
      } else if (role === 'seller') {
        query.seller = userId;
      } else {
        // 'all' - 查询与用户相关的所有订单
        query.$or = [{ buyer: userId }, { seller: userId }];
      }

      // 状态筛选
      if (status) {
        query.status = status;
      }

      // 构建排序
      const sortOption = {};
      sortOption[sort] = order === 'asc' ? 1 : -1;

      // 计算分页
      const skip = (Number(page) - 1) * Number(limit);

      // 查询订单
      const [orders, total] = await Promise.all([
        Order.find(query)
          .skip(skip)
          .limit(Number(limit))
          .sort(sortOption)
          .populate('buyer', 'username avatar studentId')
          .populate('seller', 'username avatar studentId')
          .populate('product', 'title price images status'),
        Order.countDocuments(query)
      ]);

      // 统计各状态订单数量
      const statusCounts = await Order.aggregate([
        { $match: query },
        {
          $group: {
            _id: '$status',
            count: { $sum: 1 }
          }
        }
      ]);

      res.json({
        success: true,
        data: {
          orders,
          total,
          page: Number(page),
          totalPages: Math.ceil(total / Number(limit)),
          statusCounts: statusCounts.reduce((acc, curr) => {
            acc[curr._id] = curr.count;
            return acc;
          }, {})
        }
      });
    } catch (error) {
      next(error);
    }
  },

  // 获取订单详情
  async getOrderDetail(req, res, next) {
    try {
      const { id } = req.params;
      const userId = req.user.userId;
      const isAdmin = req.user.role === 'admin';

      const order = await Order.findById(id)
        .populate('buyer', 'username avatar studentId phone')
        .populate('seller', 'username avatar studentId phone')
        .populate({
          path: 'product',
          select: 'title description price images status category condition',
          populate: {
            path: 'seller',
            select: 'username avatar studentId'
          }
        });

      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证权限（管理员可以查看所有订单，买家和卖家只能查看自己的订单）
      if (!isAdmin &&
        order.buyer._id.toString() !== userId &&
        order.seller._id.toString() !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权查看此订单'
        });
      }

      res.json({
        success: true,
        data: { order }
      });
    } catch (error) {
      next(error);
    }
  },

  // 更新订单状态
  async updateOrderStatus(req, res, next) {
    try {
      const { id } = req.params;
      const { status, reason } = req.body;
      const userId = req.user.userId;

      const order = await Order.findById(id)
        .populate('product', 'title status');

      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证操作权限（买家和卖家都可以操作）
      const role = order.buyer.toString() === userId ? 'buyer' :
        order.seller.toString() === userId ? 'seller' : null;

      if (!role) {
        return res.status(403).json({
          success: false,
          message: '无权操作此订单'
        });
      }

      // 验证状态转换的合法性
      const validTransitions = {
        '待见面交易': ['已完成', '已取消']
      };

      if (!validTransitions[order.status]?.includes(status)) {
        return res.status(400).json({
          success: false,
          message: '无效的状态转换'
        });
      }

      // 更新订单状态
      order.status = status;
      if (status === '已取消') {
        order.cancelReason = reason;
        // 记录是谁取消的
        order.cancelledBy = role;
        order.cancelledAt = new Date();
      }

      await order.save();

      // 根据订单状态更新商品状态
      const productStatus = {
        '已完成': '已售出',
        '已取消': '在售'
      }[status];

      if (productStatus) {
        await Product.findByIdAndUpdate(order.product._id, {
          status: productStatus
        });
      }

      // 返回更新后的订单信息
      const updatedOrder = await Order.findById(id)
        .populate('buyer', 'username avatar studentId')
        .populate('seller', 'username avatar studentId')
        .populate('product', 'title price images status');

      res.json({
        success: true,
        message: `订单${status === '已完成' ? '完成' : '取消'}成功`,
        data: { order: updatedOrder }
      });
    } catch (error) {
      next(error);
    }
  },

  // 添加评价
  async addReview(req, res, next) {
    try {
      const { id } = req.params; // 订单ID
      const { rating, comment } = req.body;
      const userId = req.user.userId; // 当前登录用户ID，即买家ID

      // 验证评价数据
      if (!rating || rating < 1 || rating > 5) {
        return res.status(400).json({
          success: false,
          message: '评分必须在1到5之间'
        });
      }
      if (!comment || comment.trim() === '') {
        return res.status(400).json({
          success: false,
          message: '评价内容不能为空'
        });
      }

      const order = await Order.findById(id);

      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 检查订单是否属于当前用户（买家）
      if (order.buyer.toString() !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权评价此订单'
        });
      }

      // 检查订单状态是否为"已完成"
      if (order.status !== '已完成') {
        return res.status(400).json({
          success: false,
          message: '只有已完成的订单才能评价'
        });
      }

      // 检查是否已评价
      if (order.review && order.review.rating) {
        return res.status(400).json({
          success: false,
          message: '订单已评价，不能重复评价'
        });
      }

      // 更新订单评价信息
      order.review = {
        rating: Number(rating),
        comment: comment.trim(),
        createdAt: new Date()
      };

      await order.save();

      // 返回更新后的订单信息（可选，根据需要调整）
      const populatedOrder = await Order.findById(id)
        .populate('buyer', 'username avatar')
        .populate('seller', 'username avatar')
        .populate('product', 'title price images');

      res.json({
        success: true,
        message: '评价成功',
        data: { order: populatedOrder }
      });
    } catch (error) {
      next(error);
    }
  }
};

// 管理员订单管理功能
const adminOrderMethods = {
  // 管理员获取所有订单列表
  async getAllOrders(req, res, next) {
    try {
      const {
        page = 1,
        limit = 10,
        status,
        buyerId,
        sellerId,
        productId,
        startDate,
        endDate,
        isDisputed,
        sort = 'createdAt',
        order = 'desc'
      } = req.query;

      // 构建查询条件
      const query = {};

      if (status) query.status = status;
      if (buyerId) query.buyer = buyerId;
      if (sellerId) query.seller = sellerId;
      if (productId) query.product = productId;

      // 日期范围筛选
      if (startDate || endDate) {
        query.createdAt = {};
        if (startDate) {
          query.createdAt.$gte = new Date(startDate);
        }
        if (endDate) {
          query.createdAt.$lte = new Date(endDate);
        }
      }

      // 争议订单筛选
      if (isDisputed === 'true') {
        query['disputeInfo.isDisputed'] = true;
      } else if (isDisputed === 'false') {
        query['disputeInfo.isDisputed'] = false;
      }

      // 构建排序
      const sortOption = {};
      sortOption[sort] = order === 'asc' ? 1 : -1;

      // 计算分页
      const skip = (Number(page) - 1) * Number(limit);

      // 执行查询
      const [orders, total] = await Promise.all([
        Order.find(query)
          .skip(skip)
          .limit(Number(limit))
          .sort(sortOption)
          .populate('buyer', 'username avatar studentId email phone status')
          .populate('seller', 'username avatar studentId email phone status')
          .populate('product', 'title price images status category condition')
          .populate('adminAction.adminId', 'username')
          .populate('disputeInfo.resolvedBy', 'username'),
        Order.countDocuments(query)
      ]);

      // 获取各种状态的订单数量
      const statusCounts = await Order.aggregate([
        {
          $group: {
            _id: '$status',
            count: { $sum: 1 }
          }
        }
      ]);

      // 获取争议订单数量
      const disputedCount = await Order.countDocuments({ 'disputeInfo.isDisputed': true });

      res.json({
        success: true,
        data: {
          orders,
          pagination: {
            total,
            page: Number(page),
            limit: Number(limit),
            pages: Math.ceil(total / Number(limit))
          },
          statusCounts: statusCounts.reduce((acc, curr) => {
            acc[curr._id] = curr.count;
            return acc;
          }, {}),
          disputedCount
        }
      });
    } catch (error) {
      next(error);
    }
  },

  // 管理员获取订单详情
  async getOrderAdmin(req, res, next) {
    try {
      const { id } = req.params;

      const order = await Order.findById(id)
        .populate('buyer', 'username avatar studentId email phone status')
        .populate('seller', 'username avatar studentId email phone status')
        .populate({
          path: 'product',
          select: 'title description price images status category condition',
          populate: {
            path: 'seller',
            select: 'username avatar studentId'
          }
        })
        .populate('adminAction.adminId', 'username')
        .populate('disputeInfo.resolvedBy', 'username');

      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      res.json({
        success: true,
        data: { order }
      });
    } catch (error) {
      next(error);
    }
  },

  // 管理员强制取消订单
  async forceCancel(req, res, next) {
    try {
      const { id } = req.params;
      const { reason } = req.body;
      const adminId = req.user.userId;

      if (!reason) {
        return res.status(400).json({
          success: false,
          message: '请提供取消原因'
        });
      }

      const order = await Order.findById(id)
        .populate('product', 'status');

      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 已完成或已取消的订单不能再强制取消
      if (['已完成', '已取消', '已强制取消'].includes(order.status)) {
        return res.status(400).json({
          success: false,
          message: `订单已${order.status}，无法取消`
        });
      }

      // 更新订单状态
      order.status = '已强制取消';
      order.cancelReason = reason;
      order.cancelledBy = 'admin';
      order.cancelledAt = new Date();
      order.adminAction = {
        action: '强制取消',
        reason,
        actionTime: new Date(),
        adminId
      };

      await order.save();

      // 将商品状态改回"在售"
      if (order.product) {
        await Product.findByIdAndUpdate(order.product._id, {
          status: '在售'
        });
      }

      res.json({
        success: true,
        message: '订单已强制取消',
        data: { order }
      });
    } catch (error) {
      next(error);
    }
  },

  // 管理员处理争议订单
  async resolveDispute(req, res, next) {
    try {
      const { id } = req.params;
      const { resolution, action } = req.body;
      const adminId = req.user.userId;

      if (!resolution) {
        return res.status(400).json({
          success: false,
          message: '请提供处理结果'
        });
      }

      if (!['保持原状', '完成订单', '取消订单'].includes(action)) {
        return res.status(400).json({
          success: false,
          message: '无效的处理操作'
        });
      }

      const order = await Order.findById(id);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 检查是否为争议订单
      if (!order.disputeInfo || !order.disputeInfo.isDisputed) {
        return res.status(400).json({
          success: false,
          message: '此订单没有争议标记'
        });
      }

      // 更新争议信息
      order.disputeInfo.resolution = resolution;
      order.disputeInfo.resolvedAt = new Date();
      order.disputeInfo.resolvedBy = adminId;

      // 记录管理员操作
      order.adminAction = {
        action: action === '保持原状' ? '其他' : action === '完成订单' ? '完成订单' : '强制取消',
        reason: resolution,
        actionTime: new Date(),
        adminId
      };

      // 根据操作更新订单状态
      if (action === '完成订单') {
        order.status = '已完成';
        // 更新商品状态为已售出
        await Product.findByIdAndUpdate(order.product, {
          status: '已售出'
        });
      } else if (action === '取消订单') {
        order.status = '已强制取消';
        order.cancelReason = resolution;
        order.cancelledBy = 'admin';
        order.cancelledAt = new Date();
        // 更新商品状态为在售
        await Product.findByIdAndUpdate(order.product, {
          status: '在售'
        });
      }

      await order.save();

      res.json({
        success: true,
        message: '争议已处理',
        data: { order }
      });
    } catch (error) {
      next(error);
    }
  },

  // 管理员标记争议订单
  async markDispute(req, res, next) {
    try {
      const { id } = req.params;
      const { reason } = req.body;
      const adminId = req.user.userId;

      if (!reason) {
        return res.status(400).json({
          success: false,
          message: '请提供争议原因'
        });
      }

      const order = await Order.findById(id);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 只有已完成状态的订单才可以标记为争议
      if (order.status !== '已完成') {
        return res.status(400).json({
          success: false,
          message: `订单必须是已完成状态才能标记为争议，当前状态: ${order.status}`
        });
      }

      // 标记为争议订单
      order.disputeInfo = {
        isDisputed: true,
        reason,
        reportedBy: 'system',
        reportedAt: new Date()
      };

      order.adminAction = {
        action: '其他',
        reason: `标记争议：${reason}`,
        actionTime: new Date(),
        adminId
      };

      await order.save();

      res.json({
        success: true,
        message: '订单已标记为争议',
        data: { order }
      });
    } catch (error) {
      next(error);
    }
  }
};

// 用户（买家或卖家）报告订单争议
const userOrderMethods = {
  async reportDispute(req, res, next) {
    try {
      const { id } = req.params;
      const { reason } = req.body;
      const userId = req.user.userId;

      if (!reason) {
        return res.status(400).json({
          success: false,
          message: '请提供争议原因'
        });
      }

      const order = await Order.findById(id);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证用户是订单的买家或卖家
      const isBuyer = order.buyer.toString() === userId;
      const isSeller = order.seller.toString() === userId;

      if (!isBuyer && !isSeller) {
        return res.status(403).json({
          success: false,
          message: '您不是此订单的买家或卖家'
        });
      }

      // 只有已完成状态的订单才可以标记为争议
      if (order.status !== '已完成') {
        return res.status(400).json({
          success: false,
          message: `订单必须是已完成状态才能标记为争议，当前状态: ${order.status}`
        });
      }

      // 检查是否已经有争议标记
      if (order.disputeInfo && order.disputeInfo.isDisputed) {
        return res.status(400).json({
          success: false,
          message: '此订单已有争议标记'
        });
      }

      // 标记为争议订单
      order.disputeInfo = {
        isDisputed: true,
        reason,
        reportedBy: isBuyer ? 'buyer' : 'seller',
        reportedAt: new Date()
      };

      await order.save();

      res.json({
        success: true,
        message: '订单已标记为争议',
        data: { order }
      });
    } catch (error) {
      next(error);
    }
  }
};

// 合并所有方法
module.exports = {
  ...orderController,
  ...adminOrderMethods,
  ...userOrderMethods
}; 